import { defineComponent, PropType } from 'vue'
import { ElMessage } from 'element-plus'
import { baseURL } from '@/utils/config'

export default defineComponent({
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    onSussess: {
      type: Function as PropType<(res: any) => void>,
      required: true
    },
    onStart: {
      type: Function as PropType<() => void>
    },
    onEnd: {
      type: Function as PropType<() => void>
    }
  },
  setup (props, { slots }) {
    const beforeUpload = (file: any) => {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImg) {
        ElMessage.error('只能上传图片')
      }
      if (!isLt5M) {
        ElMessage.error('图片不能大于5m')
      }
      return isImg && isLt5M
    }

    const progress = () => {
      if (props.onStart) props.onStart()
    }

    const onSuccess = (response: any, file: any, fileList: any) => {
      props.onSussess(response)
      ElMessage.success('上传成功')
      if (props.onEnd) props.onEnd()
    }

    const onError = () => {
      ElMessage.error('上传失败')
      if (props.onEnd) props.onEnd()
    }

    return () => {
      return <el-upload
        action={baseURL + '/api/utils/upload'}
        before-upload={beforeUpload}
        with-credentials={true}
        show-file-list={false}
        on-progress={progress}
        name="file"
        on-success={onSuccess}
        on-error={onError}
        multiple={props.multiple}
      >
        {slots}
      </el-upload>
    }
  }
})
